#pragma once
using namespace std;
#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>

const int defaultcap=5;

template <class T>
class BlockQueue
{
public:
    BlockQueue()
    :_cap(defaultcap)
    ,_csleep_num(0)
    ,_psleep_num(0)
    {
        pthread_mutex_init(&_lock,nullptr);
        pthread_cond_init(&_cond_con,nullptr);
        pthread_cond_init(&_cond_pro,nullptr);
    }
    void Equeue(const T &in)
    {
        pthread_mutex_lock(&_lock);
        while(IsFull())
        {
            _psleep_num++;
            cout<<"生产者休眠中"<<endl;
            pthread_cond_wait(&_cond_pro,&_lock);
            _psleep_num--;
            
        }
        _queue.push(in);
        if(_csleep_num>0)
        {
            pthread_cond_signal(&_cond_con);
            cout<<"唤醒消费者"<<endl;
        }   
        pthread_mutex_unlock(&_lock);      
    }
    T Pop()
    {
        pthread_mutex_lock(&_lock);
        while(IsEmpty())
        {
            _csleep_num++;
            pthread_cond_wait(&_cond_con,&_lock);
            _csleep_num--;
        }
        T data = _queue.front();
        _queue.pop();
        if(_psleep_num>0)
        {
            pthread_cond_signal(&_cond_pro);
            cout<<"唤醒生产者"<<endl;
        }
        pthread_mutex_unlock(&_lock);
        return data;
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond_pro);
        pthread_cond_destroy(&_cond_con);
    }
private:
    bool IsFull()
    {
        return _queue.size()== _cap;
    }
    bool IsEmpty()
    {
        return _queue.size() == 0;
    }
    queue<T> _queue;
    size_t _cap;
    pthread_mutex_t _lock;
    pthread_cond_t _cond_pro;
    pthread_cond_t _cond_con;

    int _csleep_num;
    int _psleep_num;
};